<template>
	<div id="follow-wrapper" class="shadow">
		<!-- 用户进入公众号和用户关注公众号 -->
		<div class="top-title flex between">
			<span>{{top_title}}</span>
			<div v-if="top_title=='用户进入公众号'" class="tips flex center">使用此功能的服务号必须开启<span style="padding: 2px 4px;font-size: 90%;color: #c7254e;background-color: #f9f2f4;border-radius: 4px;">获取用户地理位置</span>的接口权限，
				<Poptip placement="right" trigger="hover" word-wrap width="200" content="登录微信公众平台，点击左侧菜单【开发 / 接口权限】，找到类目中的【对话服务 / 用户管理 / 获取用户地理位置】，点击开启按钮并配置为每次上报">
					<div class="flex center">
						<div style="margin-right:3px;font-size:10px;border-radius:7px; background: #2d8cf0; width:14px;height:14px;text-align:center;line-height:16px;color:white;">?</div>
						<a href="javascript:">如何开启</a>
					</div>
				</Poptip>
			</div>
		</div>

		<!--顶部回复类型单选项-->
		<Form :label-width="120" style="padding: 20px;padding-bottom: 0;" label-position="left">
			<FormItem label="自动回复内容" prop="replyType">
				<div class="flex column">
					<RadioGroup @on-change='change' v-model="replyType">
						<Radio :label="item.value" v-for="item in replyList" :key="'reply'+item.label">
							<span>{{item.label}}</span>
						</Radio>
					</RadioGroup>
					<span v-if="top_title=='用户进入公众号'&&replyType=='text'" style="color:#6F6C6C;">用户进公众号就会收到自动回复的小程序链接<span style="color: red;margin-left: 10px;">24小时内重复进入只发1次</span></span>
				</div>				
	        </FormItem>
		</Form>

		<!--回复纯文本-->
		<div class="reply-single-text" v-if="replyType=='text'">
			<div class="follow-content flex">
				<div class="flex column Flex">
					<Form ref="replyText" :label-width="120" :model='replyMiniprogram' :rules='replyTextRule' label-position="left">
						<FormItem label="自动回复内容" prop="text_content">
							<div class="flex column start">
								<div style="margin-bottom: 15px;">
									<Button type="primary" @click="showAddMiniprogramLink=true">添加小程序链接</Button>
								</div>
								<Input id="replyText" type="textarea" style="width: 70%;" :rows="10" v-model="replyMiniprogram.text_content" placeholder="自动回复内容"></Input>
								<p style="color: gray;">文案内容如果包含粉丝昵称，请用 <span style="color:red;">{nickname}</span> 代替</p>
								<p style="color: gray;">{{replyMiniprogram.notify}}</p>
							</div>	
						</FormItem>
					</Form>
					<div>
						<Button type="primary" @click="handleSubmit('replyText')" style="margin-left: 120px;">
							保存
						</Button>
					</div>
				</div>
				<div class="disFlex vertical">
					<p class="demo-title">消息预览</p>
					<div class="preview-wrapper disFlex">
						<img :src="replyMiniprogram.logo" alt="">
						<p v-html="reply_text_html"></p>
					</div>	
					<p class="demo-title">示意</p>
					<img class="img-demo-reply-text" :src="replyMiniprogram.remind_image_text" alt=""/>
				</div>
			</div>
			
		</div>

		<!--回复小程序卡片-->
		<div class="reply-miniprogram" v-else-if="replyType=='miniprogram'">
			<div class="flex">
				<div class="Flex">
					<Form ref="replyMiniprogram" :label-width="120" :model='replyMiniprogram' :rules='replyMiniprogramRule' label-position="left">
						<FormItem label="小程序卡片路径" prop="miniprogram_page_path">
							<div class="flex center">
								<Select v-model="replyMiniprogram.miniprogram_page_path_opt"  @on-change="chageSel()" class="select-wrapper">
									<Option :value=0>首页</Option>
									<Option :value=1>微页面</Option>
									<Option :value=2>商品</Option>
									<Option :value=3>企业</Option>
								</Select>
								<Input style="width: 300px;" readonly v-model="replyMiniprogram.miniprogram_page_path" @click.native="tapInput" placeholder="请选择卡片路径"></Input>
							</div>
						</FormItem>
						<FormItem label="小程序卡片标题" prop="miniprogram_title">
							<Input style="width: 300px;" v-model="replyMiniprogram.miniprogram_title" placeholder="小程序卡片标题"></Input>
						</FormItem>
						<FormItem label="小程序卡片图片" prop="miniprogram_page_thumb_url">
							<div class="upload-operate-wrapper">
								<Button type="primary" ghost class="upload-img-btn">
									上传图片
									<input type="file" accept="image/gif, image/jpeg, image/png, image/jpg" @change="handleFileChange"></input>
								</Button>
								<span>推荐尺寸:1280*840格式</span>
							</div>
							<img  class="upload-img" style="width: 120px; height: 92px;" v-if="replyMiniprogram.miniprogram_page_thumb_url!=''" :src="replyMiniprogram.miniprogram_page_thumb_url"/>
						</FormItem>
						<div>
							<Button type="primary" @click="handleSubmit('replyMiniprogram')" style="margin-left: 120px;">
								保存
							</Button>
						</div>		        
					</Form>
				</div>
				<img class="img-demo-reply-miniprogram" :src="replyMiniprogram.remind_image_miniprogram" alt=""/>
			</div>
		</div>

		<!--不回复-->
		<div class="no-reply" v-else>
			<Form ref="replyMiniprogram" :label-width="120" style="padding: 0 20px;">
		        <FormItem label="" prop="">
					<Button type="primary" @click="handleSubmit('noreply')">保存</Button>
				</FormItem>
			</Form>
		</div>

		<!-- 添加小程序链接弹框 -->
		<Modal v-model="showAddMiniprogramLink">
	        <p slot="header" style="color:rgb(8, 93, 196);text-align:center">
	            <span>添加小程序链接</span>
	        </p>
	        <div class="model-miniprogram-wrapper">
		        <Form ref="modelMiniprogram" :label-width="120" :model='modelMiniprogram' :rules='modelMiniprogramRule' label-position="left">
					<FormItem label="小程序卡片路径" prop="miniprogram_path">
						<div class="flex center">
							<Select v-model="modelMiniprogram.miniprogram_type"  @on-change="choseMiniprogramType()" class="select-wrapper">
								<Option :value=0>首页</Option>
								<Option :value=1>微页面</Option>
								<Option :value=2>商品</Option>
								<Option :value=3>企业</Option>
							</Select>
							<Input style="width: 250px;" readonly v-model="modelMiniprogram.miniprogram_path" @click.native="tapModelInput" placeholder="请选择跳转路径"></Input>
						</div>
					</FormItem>
					<FormItem label="链接文案" prop="link_title">
						<Input style="width: 300px;" v-model="modelMiniprogram.link_title" placeholder="小程序卡片标题"></Input>
					</FormItem>
				</Form>
	        </div>
	        <div slot="footer">
	            <div class="flex center column-center">
					<Button @click="showAddMiniprogramLink=false">取消</Button>
	            	<Button type="primary" @click="saveModal">保存</Button>
				</div>
	        </div>
	    </Modal>
		
		<!-- 商品选择器 -->
		<goodsSelect buyMode="-9" @confirm="commitGoodsFn" :selectNum="1" ref="goodsModal"></goodsSelect>
		<!-- 微页面选择器 -->
		<micropage-select ref="micropageModal" @confirm="chosePages"></micropage-select>
		<!-- 企业选择器 -->
   	    <shop-select ref="shopselect" @commitShopFn="commitShopFn"></shop-select>
	</div>
</template>

<script>
	import { uploadImage } from 'api/uploadImage'
	// 商品选择器组件
	import goodsSelect from 'base/goods-select/goods-select'
	// 企业选择器
	import shopSelect from 'base/shopSelect/shopSelect'
	// 微页面选择器组件
	import MicropageSelect from 'base/micropage-select/micropage-select'
	
	import { subscribeConfig,subscribeConfigEdit,intoConfig,intoConfigEdit } from "api/wechatSetting"

	export default {
        data () {
            return {
				spinShow: false,
				showAddMiniprogramLink: false,
				subscribeType: "openReply",
				replyList: [
					{
						label: '回复纯文本',
						value: "text"
					},
					{
						label: '回复小程序卡片',
						value: "miniprogram"
					},
					{
						label: '不回复内容',
						value: "none"
					}
				],
				// 添加小程序链接表单
				modelMiniprogram: {
					// 路径类型
					miniprogram_type: 0,
					// 跳转路径
					miniprogram_path: "app/mallA/index/index",
					// 链接文案
					link_title: ""
				},
				// 添加小程序链接表单规则
				modelMiniprogramRule: {
					miniprogram_path: [{ required: true, message: '小程序链接不能为空', trigger: 'change' }],
					link_title: [{ required: true, message: '小程序链接文案不能为空', trigger: 'blur' }]
				},

				// 回复表单
				replyMiniprogram: {
					// 关键词
					receive_keyword: "",
					// 回复类型 text文本信息 miniprogram 小程序卡片
					reply_type: "miniprogram", 
					// 小程序卡片路径类型
					miniprogram_page_path_opt: 0,
					// 小程序卡片路径
					miniprogram_page_path: "app/mallA/index/index",
					// 小程序卡片标题
					miniprogram_title: "",
					// 小程序卡片图片
					miniprogram_page_thumb_url: "",
					// 回复文本内容
					text_content: "",
					// 小程序卡片预览图片
					remind_image_miniprogram: "",
					// 小程序链接预览图片
					remind_image_text: ""
				},
				replyMiniprogramRule: {
					miniprogram_page_path: [{ required: true, message: '小程序卡片路径不能为空', trigger: 'change' }],
					miniprogram_title: [{ required: true, message: '小程序卡片标题不能为空', trigger: 'blur' }],
					miniprogram_page_thumb_url: [{ required: true, message: '小程序卡片图片不能为空', trigger: 'blur' }]
				},
				replyTextRule: {
					text_content: [{ required: true, message: '回复内容不能为空', trigger: 'blur' }]
				},
				
				replyType:1,
				reply: '',
            		
			}
        },
        methods: {
			getData() {
				if (this.subscribeType == "openReply") {
					console.log('进入公众号')
					// 进入公众号
					intoConfig().then(_res=>{
						this.spinShow = false;
						this.replyMiniprogram = _res.data;
						this.wechatAppid = _res.data.wechat_app_id;
						this.replyType = _res.data.reply_type;
					}).catch(err=>{
						this.spinShow = false;
						this.$Message.error(err.message);
					})
				} else {
					// 关注公众号
					subscribeConfig().then(_res=>{
						this.spinShow = false;
						this.replyMiniprogram = _res.data;
						this.wechatAppid = _res.data.wechat_app_id;
						this.replyType = _res.data.reply_type;
					}).catch(err=>{
						this.spinShow = false;
						this.$Message.error(err.message);
					})
				}
				
			},
			// 卡片路径类型切换
			chageSel() {
				if (this.replyMiniprogram.miniprogram_page_path_opt == 0) {
					this.replyMiniprogram.miniprogram_page_path = "app/mallA/index/index";
				} else {
					this.replyMiniprogram.miniprogram_page_path = "";
				}
			},

			// 小程序链接卡片路径类型切换
			choseMiniprogramType() {
				if (this.modelMiniprogram.miniprogram_type == 0) {
					this.modelMiniprogram.miniprogram_path = "app/mallA/index/index";
				} else {
					this.modelMiniprogram.miniprogram_path = "";
				}
			},

			tapInput() {
				this.choseType = 0;
				if (this.replyMiniprogram.miniprogram_page_path_opt == 1) { 
					// 微页面
					this.$refs.micropageModal.show();
				} else if (this.replyMiniprogram.miniprogram_page_path_opt == 2) { 
					// 商品
					this.$refs.goodsModal.show()
				} else if (this.replyMiniprogram.miniprogram_page_path_opt == 3) { 
					// 企业
					this.$refs.shopselect.openFn("");
				}
			},
			tapModelInput() {
				this.choseType = 1;
				if (this.modelMiniprogram.miniprogram_type == 1) { 
					// 微页面
					this.$refs.micropageModal.show();
				} else if (this.modelMiniprogram.miniprogram_type == 2) { 
					// 商品
					this.$refs.goodsModal.show()
				} else if (this.modelMiniprogram.miniprogram_type == 3) { 
					// 企业
					this.$refs.shopselect.openFn("");
				}
			},

			// 更新数据
			handleSubmit (name) {
				if (name == 'noreply') {
					this.replyMiniprogram.reply_type = this.replyType;
					if (this.subscribeType == "openReply") {
						// 用户进入公众号
						intoConfigEdit(this.replyMiniprogram).then(_res=>{
							this.spinShow = false;
							this.$Message.success("更新成功");
						}).catch(err=>{
							this.spinShow = false;
							this.$Message.error(err.message);
						})
					} else {
						// 用户关注公众号
						subscribeConfigEdit(this.replyMiniprogram).then(_res=>{
							this.spinShow = false;
							this.$Message.success("更新成功");
						}).catch(err=>{
							this.spinShow = false;
							this.$Message.error(err.message);
						})
					}
				} else {
					this.$refs[name].validate((valid) => {
						if (valid) {
							this.replyMiniprogram.reply_type = this.replyType;
							if (this.subscribeType == "openReply") {
								console.log(789)
								// 用户进入公众号
								intoConfigEdit(this.replyMiniprogram).then(_res=>{
									this.spinShow = false;
									this.$Message.success("更新成功");
								}).catch(err=>{
									this.spinShow = false;
									this.$Message.error(err.message);
								})
							} else {
								// 用户关注公众号
								subscribeConfigEdit(this.replyMiniprogram).then(_res=>{
									this.spinShow = false;
									this.$Message.success("更新成功");
								}).catch(err=>{
									this.spinShow = false;
									this.$Message.error(err.message);
								})
							}
							
						} else {
							this.$Message.error('请填写完整信息!');
						}
					})
				}
				
			},
			
		
			handleFileChange (event) {
				var that = this;
				uploadImage(event.target.files[0]).then(imgUrl => {
					that.replyMiniprogram.miniprogram_page_thumb_url = imgUrl;
				}).catch(err => {
					that.$Message.error(err);  
				})  
			},

			// 选中商品回调
			commitGoodsFn(_id){
				if (this.choseType == 0) {
					// 回复小程序卡片选择
					if (_id != "") {
						this.replyMiniprogram.miniprogram_page_path = "app/mall/item/item?goodsId="+_id;
					} else {
						this.replyMiniprogram.miniprogram_page_path = "";
					}
				} else {
					// 弹窗选择
					if (_id != "") {
						this.modelMiniprogram.miniprogram_path = "app/mall/item/item?goodsId="+_id;
					} else {
						this.modelMiniprogram.miniprogram_path = "";
					}
				}
			},

			// 选中微页面回调
			chosePages(ids) {
				if (this.choseType == 0) {
					// 回复小程序卡片选择
					if (ids.length>0) {
						this.replyMiniprogram.miniprogram_page_path = "app/mall/label/label?labelId="+ids[0];
					} else {
						this.replyMiniprogram.miniprogram_page_path = "";
					}
				} else {
					// 弹窗选择
					if (ids.length>0) {
						this.modelMiniprogram.miniprogram_path = "app/mall/label/label?labelId="+ids[0];
					} else {
						this.modelMiniprogram.miniprogram_path = "";
					}
				}
			},

			// 企业选中回调
			commitShopFn(arr){
				if (this.choseType == 0) {
					// 回复小程序卡片选择
					if (arr.length > 0) {
						this.replyMiniprogram.miniprogram_page_path = "app/shop/index/index?shopId=" + arr[0].shop_id;
					} else {
						this.replyMiniprogram.miniprogram_page_path = "";
					}
				} else {
					// 弹窗选择
					if (arr.length > 0) {
						this.modelMiniprogram.miniprogram_path = "app/shop/index/index?shopId=" + arr[0].shop_id;
					} else {
						this.modelMiniprogram.miniprogram_path = "";
					}
				}
				
			},

			// 保存弹框添加小程序链接内容
			saveModal() {
				this.$refs.modelMiniprogram.validate((valid) => {
					if (valid) {
						this.showAddMiniprogramLink = false;
						var title = `<a data-miniprogram-appid="${this.wechatAppid}" data-miniprogram-path="${this.modelMiniprogram.miniprogram_path}"  href="http://">${this.modelMiniprogram.link_title}</a>`;
						this.addCursor(document.getElementById("replyText").children[0], title);
					} else {
						this.$Message.error('请填写完整信息!');
					}
				})
			},

			// 获取光标位置
			getCursor(textarea) {
				var rangeData = {text: "", start: 0, end: 0 };
				if (textarea.setSelectionRange) { // W3C	
					textarea.focus();
					rangeData.start= textarea.selectionStart;
					rangeData.end = textarea.selectionEnd;
					rangeData.text = (rangeData.start != rangeData.end) ? textarea.value.substring(rangeData.start, rangeData.end): "";
				} else if (document.selection) { // IE
					textarea.focus();
					var i,
						oS = document.selection.createRange(),
						// Don't: oR = textarea.createTextRange()
						oR = document.body.createTextRange();
					oR.moveToElementText(textarea);
					
					rangeData.text = oS.text;
					rangeData.bookmark = oS.getBookmark();
					
					// object.moveStart(sUnit [, iCount]) 
					// Return Value: Integer that returns the number of units moved.
					for (i = 0; oR.compareEndPoints('StartToStart', oS) < 0 && oS.moveStart("character", -1) !== 0; i ++) {
						// Why? You can alert(textarea.value.length)
						if (textarea.value.charAt(i) == '\r' ) {
							i ++;
						}
					}
					rangeData.start = i;
					rangeData.end = rangeData.text.length + rangeData.start;
				}
				return rangeData;
			},
			// 设置光标位置
			setCursor(textarea, rangeData) {
				var oR, start, end;
				textarea.focus();
				if (textarea.setSelectionRange) { // W3C
					textarea.setSelectionRange(rangeData.start, rangeData.end);
				} else if (textarea.createTextRange) { // IE
					oR = textarea.createTextRange();
					// Fixbug : ues moveToBookmark()
					// In IE, if cursor position at the end of textarea, the set function don't work
					if(textarea.value.length === rangeData.start) {
						//alert('hello')
						oR.collapse(false);
						oR.select();
					} else {
						oR.moveToBookmark(rangeData.bookmark);
						oR.select();
					}
				}
			},
			// 添加文字
			addCursor(textarea, text) {
				var oValue, nValue, oR, sR, nStart, nEnd, st;
				var rangeData = this.getCursor(textarea);
				this.setCursor(textarea, rangeData);

				if (textarea.setSelectionRange) { // W3C
					oValue = textarea.value;
					nValue = oValue.substring(0, rangeData.start) + text + oValue.substring(rangeData.end);
					nStart = nEnd = rangeData.start + text.length;
					st = textarea.scrollTop;
					textarea.value = nValue;
					this.replyMiniprogram.text_content = nValue;
					// Fixbug:
					// After textarea.values = nValue, scrollTop value to 0
					if(textarea.scrollTop != st) {
						textarea.scrollTop = st;
					}
					textarea.setSelectionRange(nStart, nEnd);
				} else if (textarea.createTextRange) { // IE
					sR = document.selection.createRange();
					sR.text = text;
					this.replyMiniprogram.text_content = text;
					sR.setEndPoint('StartToEnd', sR);
					sR.select();
				}

			},
		
        },
        created() {
			// 判断配置类型 entranceWechat-用户进入公众号 subscribeWechat-用户关注公众号
			this.subscribeType = this.$route.path.split('/')[this.$route.path.split('/').length - 1];
			this.getData();
        },
        components: {
			goodsSelect,MicropageSelect,shopSelect
		},
		watch: {
			'$route'(newVal){
				this.subscribeType = newVal.path.split('/')[newVal.path.split('/').length - 1];
				this.getData();
			}
		},
		computed: {
			top_title: function() {
				return this.subscribeType == "openReply" ? "用户进入公众号" : "用户关注公众号"
			},
			reply_text_html: function() {
				let str = this.replyMiniprogram.text_content.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>');
				return str;
			}
		}
     }
</script>

<style scoped>
	#follow-wrapper {
		background: white;
		margin: 24px 24px 0 24px;
		padding: 20px;
		font-size: 14px;
		height: calc(100vh - 88px);
		overflow: auto;
	}
	.top-title {
		background: #f5f7f9;
		color: black;
		padding: 10px;
		font-size: 14px;
	}
	.tips {
		color: #aaa;
		font-size: 12px;
	}
	.follow-content {
		background: white;
		padding: 20px;
		padding-top: 0;
	}

	.reply-miniprogram {
		padding: 0 20px;
	}

	.preview-wrapper {
		width: 370px;
		min-width: 370px;
		height: 200px;
		padding: 10px;
	    background-color: rgb(233, 229, 233);
	    border: 1px solid #ddd;
	    border-radius: 4px;
	    margin-left: 20px;
	}

	.preview-wrapper img {
		width: 40px;
		min-width: 40px;
		height: 40px;
		background: gray;
		margin-right: 10px;
	}
	
	.preview-wrapper p {
		background: white;
		width: 230px;
		border-radius: 5px;
		padding: 10px;
		color: black;
		font-size: 16px;
		overflow-y: auto;
		word-wrap: break-word;
	}

	.img-demo-reply-text {
		display: inline-block;
	    width: 370px;
		min-width: 370px;
	    height: 270px;
	    padding: 4px;
	    background-color: #fff;
	    border: 1px solid #ddd;
	    border-radius: 4px;
	    margin-left: 20px;
	}

	.img-demo-reply-miniprogram {
		display: inline-block;
	    width: 370px;
	    min-width: 370px;
	    height: 380px;
	    padding: 4px;
	    background-color: #fff;
	    border: 1px solid #ddd;
	    border-radius: 4px;
	    margin-left: 20px;
	}
	/* p {
		color: #aaa;
		font-size: 13px;
	} */
	
	/*上传图片*/
	.upload-operate-wrapper {
		display: flex;
	}
	.upload-operate-wrapper span {
		color: darkgray;
		margin-left: 6px;
	}
	.upload-img-btn {
		position: relative;
	}
	.upload-img-btn input {
		position: absolute;
		opacity: 0;
		left: 0;top: 0;width: 100%;height: 100%;
	}
	.upload-img {
		width: 284px;
		margin-top: 10px;
		border: 1px solid #F2F2F2;
	}

	.select-wrapper {
		width: 128px;
		margin-right: 15px;
	}

	.demo-title {
		text-align: center;
		padding: 10px;
		color: black;
	}
</style>